package com.ycb.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicHeader;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author 黄泽群
 * @since 2024-01-16
 */
@Slf4j
public class JdApiUtil {

    /**
     * 获取京东登入二维码
     * @param qrCodePath    二维码保存路径
     * @return  {@link String 二维码扫描状态Token}
     * @throws IOException
     */
    public static String getQrCoke(String qrCodePath) throws IOException {
        final String filePath = StrUtil.isBlank(qrCodePath) ? "QrCode.png" : qrCodePath;
        String url ="https://qr.m.jd.com/show?appid=133&size=147&t=" + System.currentTimeMillis();
        HttpClientUtil.httpGet(url,(entity)->{
            try {
                // 使用try-with-resources确保资源自动关闭
                InputStream inputStream = entity.getContent();
                if (inputStream == null) {
                    throw new IllegalArgumentException("Entity content stream is null");
                }
                try (OutputStream outputStream = Files.newOutputStream(Paths.get(filePath))) {
                    byte[] buffer = new byte[1024]; // 可以根据实际情况考虑调整缓冲区大小
                    int length;
                    while ((length = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, length);
                    }
                } // 资源会在这里自动关闭
            } catch (IOException e) {
                throw new RuntimeException("Failed to write entity content to file", e);
            }

        },new BasicHeader(Constant.REFERER, Constant.REFERER_ARG_LOGIN));
        return HttpClientUtil.getCookieValue("wlfstk_smdl");
    }

    /**
     * 检查二维码状态
     * @param token   二维码状态
     * @return {@link String 登入成功返回ticket}
     * @throws IOException
     */
    public static String checkQrCode(String token) throws IOException {
        String prefix = "jQuery" + (int) ((Math.random() * (9999999 - 1000000 + 1)) + 1000000);
        String url = "https://qr.m.jd.com/check?appid=133&callback="+prefix + "&token=" + token + "&_=" + System.currentTimeMillis();
        StringBuilder sb =  new StringBuilder();
        HttpClientUtil.httpGet(url,(entity)->{
            // 获取响应信息
            String string = "";
            try {
                string = EntityUtils.toString(entity);
            } catch (Exception e) {
            }
            sb.append(string);

        },new BasicHeader(Constant.REFERER, Constant.REFERER_ARG_LOGIN));
        String result = parseJSONP(sb.toString(), prefix);
        JSONObject resultJson = JSONObject.parseObject(result);
        log.info("二维码状态 : {} \n {}",resultJson.getString("msg"),result);
        Integer code = resultJson.getInteger("code");
        if (code == 257){
            log.error("二维码失效退出系统");
            System.exit(-1);
        }
        return code == 200 ? resultJson.getString("ticket") : "";
    }

    public static void getWareBusiness(String skuId) throws IOException {
        String url = "https://item-soa.jd.com/getWareBusiness?skuId=" + skuId;
        StringBuilder sb =  new StringBuilder();
        HttpClientUtil.httpGet(url,(entity)->{
            // 获取响应信息
            String string = "";
            try {
                string = EntityUtils.toString(entity,"utf-8");
            } catch (Exception e) {
            }
            sb.append(string);

        },new BasicHeader(Constant.REFERER,  Constant.REFERER_ARG_LOGIN));
        log.info("data : {}",sb);
    }


    public static void qrCodeTicketValidation(String ticket) throws IOException {
        String url = "https://passport.jd.com/uc/qrCodeTicketValidation?t=" + ticket;
        StringBuilder sb =  new StringBuilder();
        HttpClientUtil.httpGet(url,(entity)->{
            // 获取响应信息
            String string = "";
            try {
                string = EntityUtils.toString(entity);
            } catch (Exception e) {
            }
            sb.append(string);

        },new BasicHeader(Constant.REFERER,  Constant.REFERER_ARG_LOGIN));

    }

    /**
     * 检查登入状态
     * @return {@link Boolean}
     */
    public static boolean checkLogin(){
        String jdNickName = HttpClientUtil.getCookieValue("unick");
        if (StrUtil.isNotBlank(jdNickName)){
            System.out.println("登入成功 :" +jdNickName);
            return true;
        }
        return false;
    }

    private static String parseJSONP(String data,String prefix){
        if (StrUtil.isBlank(data)){
            return "";
        }
        return data.substring(prefix.length()+1,data.length()-1);
    }

    public static void getUserInfo() throws IOException {
        String prefix = "jQuery" + (int) ((Math.random() * (9999999 - 1000000 + 1)) + 1000000);
        String url = "https://passport.jd.com/user/petName/getUserInfoForMiniJd.action?callback="+prefix;
        StringBuilder sb =  new StringBuilder();
        HttpClientUtil.httpGet(url,(entity)->{
            // 获取响应信息
            String string = "";
            try {
                string = EntityUtils.toString(entity);
            } catch (Exception e) {
                e.printStackTrace();
            }
            sb.append(string);

        },new BasicHeader(Constant.REFERER, "https://order.jd.com/center/list.action"));
        String data = parseJSONP(sb.toString(), prefix);
        JSONObject userInfo = JSONObject.parseObject(data);
        log.info("用户昵称 : {}",userInfo.getString("nickName"));
        log.info("用户等级 : {}",userInfo.getInteger("userLevel"));
        log.info("京东享值 : {}",userInfo.getJSONObject("userScoreVO").get("totalScore"));
    }


    public static void main(String[] args) throws Exception {

//        if (checkLogin()) {
//            getUserInfo();
//        }
//        String token = getQrCoke("");
//        do{
//            String ticket = checkQrCode(token);
//            if (StrUtil.isNotBlank(ticket)) {
//                System.err.println("登入成功");
//                qrCodeTicketValidation(ticket);
//                break;
//            }
//            TimeUnit.SECONDS.sleep(3L);
//        }while (true);
    }

}
